const QnTemplate = require('../models/index').getModel('qnTemplate')
const QnProject = require('../models/index').getModel('qnProject')

const qnTemplate = {
    /**
     * @Description: 保存问卷模板
     * @date 2021/11/10
     * @params: { Object } qnTemplate
     * @return: { Object | null }
     */
    async saveTemplate(template) {
        const option = {upsert: true, new: true, setDefaultsOnInsert: true}
        const result = await QnTemplate.findOneAndUpdate({templateId: template.templateId}, template, option)
        
        return result
    },
    async saveProject(params) {
        const option = {upsert: true, new: true, setDefaultsOnInsert: true};
        const { templateId } = params;
        const result = await QnProject.findOneAndUpdate({templateId}, params, option);
        return result
    },
    async findTemplateState({templateId}) {
        const result = await QnProject.findOne({templateId});
        console.log(result)
        return result
    },
    async changeTemplateState({templateId, state}) {
        const result = await QnProject.findOneAndUpdate({templateId}, {$set: {state}});
        console.log(result)
        return result
    },
    
    // templateId查找模板
    async findTemplate({templateId}) {
        const result = await QnTemplate.findOne({templateId})
        return result
    },
    // 分页查询所有模板
    async findTemplateList(params) {
        const { pageSize, currentPage } = params;
        // const result = QnTemplate.find().limit(pageSize).skip(pageSize * currentPage)
        const res = await QnProject.aggregate([
        // {
        //     "$project":{ title:1, templateId:1,state: 1, name: 1, createTime: 1, userName: 1 }
        // },
        {
            "$facet": {
                "total": [{"$count": "total"}],
                "data": [{
                    "$skip": pageSize * (currentPage - 1)
                }, {
                    "$limit": pageSize
                }]
            }
        }])
        const result= res[0] || {};
        const total = result.total[0] || {}
        return {
            total: total.total || 0,
            result: result.data
        }
    },
}
module.exports = qnTemplate